#include "game_scene.h"

#include <QTimer>

GameScene::GameScene(QObject *parent)
    :QGraphicsScene(parent)
{
    for(size_t i=0;i<COUNT;i++){
        MyItem* item=new MyItem();
        QRectF rect=item->boundingRect();
        item->setPos(i%4*rect.width(),i/4*rect.height());
        this->addItem(item);

        //lambda 表达式. c++11的特性 作用:创建一个匿名的函数,并可以赋值给函数指针或者是仿函数
        item->beatHamster=[this](){
            emit beatHamster();
        };
        this->itemList.push_back(item);
    }

    //创建计时器
    timer=new QTimer();
    connect(timer,&QTimer::timeout,this,&GameScene::showHamster);
}

GameScene::~GameScene()
{
    delete timer;
    for(auto item:itemList){
        delete item;
    }
}

void GameScene::showHamster()
{
    //随机出现的地鼠数量
    int count=qrand()%3+1;
    //将原来的地鼠回到洞里
    for(auto& item:itemList){
        item->setState(State::empty);
    }

    //随机出现3个地鼠
    for(int i=0;i<count;i++){
        size_t index=rand()%this->itemList.size();
        this->itemList[index]->setState(State::show_hamster);
    }
}

void GameScene::startGame()
{
    for(auto& item:itemList){
        item->setStart(true);
    }

    //开始定时器
    timer->start(1000);
}

void GameScene::pauseGame()
{
    timer->stop();
    for(auto& item:itemList){
        item->setStart(false);
    }
}

void GameScene::stopGame()
{
    this->timer->stop();
    for(auto& item:itemList){
        item->setStart(false);
        item->setState(State::empty);
    }
}
